package com.wisezone.workflow.dao.hibernate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.wisezone.common.dao.impl.BaseHibernateDaoImpl;
import com.wisezone.workflow.bean.WfActivity;
import com.wisezone.workflow.bean.search.WfActivitySearch;
import com.wisezone.workflow.dao.WfActivityDao;
import com.wisezone.workflow.exception.WfDaoException;

/**
 * hiberante 活动实现类
 * 
 * @author tss 2009-09-05
 * 
 */
public class WfActivityDaoImpl extends BaseHibernateDaoImpl implements
		WfActivityDao {

	public WfActivityDaoImpl() {
		super();
	}

	/**
	 * 获得中间活动列表
	 * 
	 * @param processDefId
	 * @return
	 * @throws WfDaoException
	 */
	public List<WfActivity> getMiddleList(Long processDefId)
			throws WfDaoException {

		WfActivitySearch searchEntity = new WfActivitySearch();
		searchEntity.setProcessDefId(processDefId);
		searchEntity.addSqlClause(" category != 9 and category != 10 ");
		return this.listAll(searchEntity);
	}

	/**
	 * 获得非开始活动列表
	 * 
	 * @param processDefId
	 * @return
	 * @throws WfDaoException
	 */
	public List<WfActivity> getNotStartList(Long processDefId)
			throws WfDaoException {

		WfActivitySearch searchEntity = new WfActivitySearch();
		searchEntity.setProcessDefId(processDefId);
		searchEntity.addSqlClause(" category != 9 ");
		return this.listAll(searchEntity);
	}

	/**
	 * 根据活动Id 获得下一活动
	 */
	public WfActivity getNextActivity(Long aid) throws WfDaoException {

		WfActivity entity = getNextActivity(aid, null);
		return entity;
	}

	/**
	 * 根据活动id 和下一活动名称活动下一活动
	 * 
	 * @param aid
	 * @param name
	 * @return
	 * @throws WfDaoException
	 */
	public WfActivity getNextActivity(Long aid, String name)
			throws WfDaoException {

		StringBuffer sb = new StringBuffer("select t2 from WfActivity t1,WfActivity t2,WfLink t3 ");
		sb.append("where t1.id = t3.preActivityId and t2.id = t3.activityId and t1.id =: id ");
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("id", aid);
		if(StringUtils.isNotEmpty(name)){
			sb.append(" and t1.name =: name ");
			map.put("name", name);
		}
		String hql = sb.toString();
		return this.get(hql, map);
		
	}

	/**
	 * 根据流程模板Id删除
	 * 
	 * @param id
	 * @throws WfDaoException
	 */
	public void deleteByProcessDefId(Long id) throws WfDaoException {
		
		String hql = "delete from WfActivity t where t.processDefId = ? ";
		this.execute(hql, id);
	}

}